/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018-12-13 Time: 22:23
 * OrderSweepScurrySave
 * 赶房 {"whsk_Order_Sweep":{"room":"0411","wuserid":"S03","iuserid":"S03","remark":"123456"}}
 */

import React, {Component} from 'react';
import {
    SafeAreaView,
    View,
    Text,
    Image,
    TouchableOpacity,
    ScrollView,
    FlatList,
    Modal, Platform, BackHandler, ToastAndroid, TextInput,
} from 'react-native';
import {connect} from 'react-redux';
import {styles} from './rmm_lose_screen.Style'
import DividingLineViewComponent from "../../../component/DividingLineViewComponent/DividingLineViewComponent";
import AntDesign from "react-native-vector-icons/AntDesign";
import FontAwesome from "react-native-vector-icons/FontAwesome"
import DatePicker from 'react-native-datepicker'
import {
    COLOR_FOCUS,
    COLOR_HEADER_END,
    COLOR_HEADER_START, COLOR_LINK,
    COLOR_THEME,
    FONT_COLOR_SUB_TITLE, FONT_COLOR_TITLE,
    FONT_SIZE_TITLE
} from "../../../constant/PHColors";
import BottomButtonView from "../../../component/BottomButtonView/BottomButtonView";
import {FetchStatus} from "../../../configuration/RequestConfiguration";
import {ReturnStatus} from "../../../configuration/ReturnStatus";
import {doDisplayWarnMessage} from "../../../component/Message/Action";
import {SCREEN_WIDTH} from "../../../constant/PHScreen";
import SelectDatePlugIn from "../../custom/selectDateTime/selectDatePlugIn";
import {retrieveHoLose,housekeepingSweepSetStatus} from "./Actions";
import {Row, Rows, Table} from "react-native-table-component";
import SelectFromBottomPlugIn from "../../custom/selectFromBottom/selectFromBottomPlugIn";

class rmm_lose extends Component {

    static navigationOptions = ({navigation}) => ({
        headerTitle: `遗留物品`,
        headerRight: (
            <TouchableOpacity activeOpacity={0.9} onPress={
                ()=>{
                    navigation.state.params.navigatePress();
                }
            }>
                <View style={{width: 80, height: 44, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
                    <Text style={{fontSize: 16, color: '#212121'}}>
                        新建
                    </Text>
                </View>
            </TouchableOpacity>
        )
    });

    // 构造
    constructor(props) {
        super(props);

        let date = new Date();
        let year = date.getFullYear().toString();
        let month = (date.getMonth()+1).toString();
        if(Number(month)<10){
            month = '0'+month
        }
        let day = date.getDate().toString();
        if(Number(day)<10){
            day = '0'+day
        }
        let opdate = year+'-'+month+'-'+day;

        this.statusSelectSel = ["all","0","1","2"];
        this.statusSelectArr = ["全部","已领取","未领取","逾期"];

        // 初始状态
        this.state = {
            room:this.props.navigation.getParam("room")?this.props.navigation.getParam("room"):'',
            hsk_status:this.props.navigation.getParam("hsk_status")?this.props.navigation.getParam("hsk_status"):'CL',
            checked:require("../../../resource/login/dl_yixuan.png"),
            uncheck:require("../../../resource/login/dl_weixuan.png"),
            startdate:opdate,
            enddate:opdate,
            reportData:[],
            showTypePop:false,
            statusSelectName: this.statusSelectArr[0],             //领取状态
            statusSelectIndex: 0,
        };

        this.tableHeader = ["流水号","状态","等级","失物","估价","描述","拾物人","报告人","报告日期","报告时间","地点","领取人","备注"];
        this.tableWidth = [80,80,80,100,80,180,80,80,100,80,150,80,180];

    }

    componentWillReceiveProps(nextProps, nextContext): void {
        let {dispatch} = this.props;


        if (nextProps.onRetrieveHoLose !== this.props.onRetrieveHoLose && nextProps.onRetrieveHoLose.fetchStatus === FetchStatus.Success) {
            if (nextProps.onRetrieveHoLose.RETURN === ReturnStatus.Success) {
                console.log(JSON.stringify(nextProps.onRetrieveHoLose.DATA))

                let rows = nextProps.onRetrieveHoLose.DATA;
                let data = [];
                rows.map((item,index)=>{
                    let status = ''
                    if(item.status ==='1'){
                        status = '未领取';
                    }else if(item.status ==='2'){
                        status = "逾期";
                    }else{
                        status = "已领取";
                    }

                    let data_son = [];
                    data_son.push(item.sn);
                    data_son.push(status);
                    data_son.push(item.grade);
                    data_son.push(item.lost_property);
                    data_son.push(item.valus);
                    data_son.push(item.bewrite);
                    data_son.push(item.collects);
                    data_son.push(item.speaker);
                    data_son.push(item.sp_date);
                    data_son.push(item.sp_time);
                    data_son.push(item.place);
                    data_son.push(item.draws);
                    data_son.push(item.remark);
                    data.push(data_son)
                });

                this.setState({
                    reportData:data,
                })
                this.reportData = data
            } else {
                // dispatch(doDisplayWarnMessage(nextProps.onRetrieveHoLose.MSG))
            }
        }

        if (nextProps.onHousekeepingSweepSetStatus !== this.props.onHousekeepingSweepSetStatus && nextProps.onHousekeepingSweepSetStatus.fetchStatus === FetchStatus.Success) {
            if (nextProps.onHousekeepingSweepSetStatus.RETURN === ReturnStatus.Success) {
                this.props.navigation.state.params.callBack()
            } else {
                // dispatch(doDisplayWarnMessage(nextProps.onHousekeepingSweepSetStatus.MSG))
            }
        }


    }

    // 组件渲染后调用
    componentDidMount() {
        let {dispatch} = this.props;

        this.props.navigation.setParams({navigatePress:this.onPressToAdd});

        this.getRecordLog();
    }

    onPressToAdd=()=> {
        let {dispatch} = this.props;
        let _this = this;
        this.props.navigation.navigate('rmm_lose_add',{callBack:()=>{
            _this.getRecordLog();
        }});
    };

    render() {
        let {dispatch} = this.props;
        let _this = this;
        return (
            <SafeAreaView style={styles.body}>
                <ScrollView style={styles.body}>
                    <View style={{backgroundColor: '#FFF'}}>
                        <View style={styles.itemHeader}>
                            <View style={styles.itemHeaderLeft}>
                                <Text style={{fontSize:16}}>请选择领取状态：</Text>
                                <TouchableOpacity  activeOpacity={0.8}  onPress={() => this._openTypeDialog()} underlayColor="#a5a5a5">
                                    <Text style={{fontSize:16,color:COLOR_LINK}}>{this.state.statusSelectName}</Text>
                                </TouchableOpacity>
                            </View>

                        </View>
                        <View style={styles.itemHeader}>
                            <View style={styles.itemHeaderLeft}>

                                <AntDesign class={'aaa'} name={'clockcircleo'} size={16} style={{color: COLOR_LINK, marginRight: 10}} />
                                <SelectDatePlugIn defaultDate={this.state.startdate} textStyle={styles.opdateViewStyle} dateBack={(date)=>{
                                    this.setState({startdate:date});
                                    let {dispatch} = this.props;

                                    let reg = new RegExp("-","g");
                                    let startdate =(date.replace(reg,""));
                                    let enddate =(this.state.enddate.replace(reg,""));
                                    this.state.startdate = startdate
                                    this.state.enddate = enddate

                                    this.getRecordLog();
                                }} />
                                <Text style={styles.opdateViewStyle}>   -   </Text>
                                <SelectDatePlugIn defaultDate={this.state.enddate} textStyle={styles.opdateViewStyle} dateBack={(date)=>{
                                    this.setState({enddate:date});
                                    let {dispatch} = this.props;

                                    let reg = new RegExp("-","g");
                                    let startdate =(this.state.startdate.replace(reg,""));
                                    let enddate =(date.replace(reg,""));

                                    this.state.startdate = startdate
                                    this.state.enddate = enddate

                                    this.getRecordLog();

                                }} />
                            </View>
                            <View style={styles.itemHeaderRight}  onPress={()=>{
                                this.getRecordLog();
                            }}>
                                <Text style={{color:COLOR_LINK}}>
                                    查询
                                </Text>
                            </View>
                        </View>

                    </View>

                    <View style={{backgroundColor: '#FFF'}}>
                        <ScrollView style={styles.body}>
                            <FlatList
                                data={[this.state.reportData]}
                                keyExtractor={(item, index) => index}
                                renderItem={this.renderTableItem}
                                horizontal={true}
                                showsHorizontalScrollIndicator={false}
                            />
                        </ScrollView>
                    </View>

                    <SelectFromBottomPlugIn entityList={this.statusSelectArr} checkedIndex={this.state.statusSelectIndex} callback={(i) => {
                        this.setState({
                            statusSelectIndex: i,
                            statusSelectName: this.statusSelectArr[i],
                        })

                        this.getRecordLog();
                    }} show={this.state.showTypePop} closeModal={(show) => {
                        this.setState({
                            showTypePop: show
                        })
                    }}/>

                </ScrollView>

            </SafeAreaView>
        )
    }

    _openTypeDialog(){
        this.setState({showTypePop: !this.state.showTypePop})
    }

    getRecordLog(){
        let {dispatch} = this.props;

        let reg = new RegExp("-","g");
        let startdate =(this.state.startdate.replace(reg,""));
        let enddate =(this.state.enddate.replace(reg,""));

        let str = " (1=1) and sp_date >= '"+startdate+"' and sp_date <= '"+enddate+"' "
        if(this.statusSelectSel[this.state.statusSelectIndex] !== "all"){
            str +=' and status = '+this.statusSelectSel[this.state.statusSelectIndex]+' '
        }
        dispatch(retrieveHoLose(str));
    }

    renderTableItem=({item})=>{
        let _this = this;
        return(
            <Table style={{marginLeft: 0}}>
                <Row data={_this.tableHeader} widthArr={_this.tableWidth} style={styles.tableHeader} textStyle={styles.tableText}/>
                <Rows data={item} widthArr={_this.tableWidth} style={styles.tableHeader} textStyle={styles.tableText}/>
            </Table>
        )
    }
}

const props = state => {
    return {
        onRetrieveHoLose:state.onRetrieveHoLose,
        onHousekeepingSweepSetStatus: state.onHousekeepingSweepSetStatus,
    }
}

export default rmm_lose = connect(props)(rmm_lose);